package com.wxxymaker.controller;

import com.wxxymaker.utils.FileUtil;
import com.wxxymaker.utils.web.ResponseWarp;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: Soft
 * @Date: 2018/5/13 17:59
 * @Desc:
 */
@RestController
public class FileHandler {

    /**
     * 文件下载
     * @param folder 文件相对static的目录
     * @param filename 文件名
     */
    @GetMapping("/download/{folder}/{filename}.{type}")
    public ResponseEntity<byte[]> download(HttpSession session, @PathVariable String folder,
                                           @PathVariable String filename, @PathVariable String type) throws IOException {
        ServletContext context = session.getServletContext();
        InputStream in = context.getResourceAsStream("/WEB-INF/static/" + folder +
                "/" + filename + "." + type);
        if ("png".equals(type)) {
            filename = "QRCode";
        }
        byte[] bs = new byte[in.available()];
        in.read(bs);
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Disposition", "attachment;filename=" + filename + "." + type);
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<byte[]>(bs, headers, HttpStatus.OK);
    }

    /**
     * 文件上传
     * 文件会被上传到static/name下面
     * @param file 文件
     * @param name 规定的文件夹/文件名，格式 folder/filename or filename
     */
    @PostMapping("/upload")
    public ResponseWarp upload(@RequestParam("file") CommonsMultipartFile file,
                               @RequestParam(defaultValue = "") String name,
                               HttpServletRequest request) {
        ServletContext context = request.getServletContext();
        if (null != file) {
            String filename = file.getOriginalFilename();
            if (!"".equals(name)) {
                filename = name;
            }
            File dest = FileUtil.createFolder(new File(context.getRealPath("/WEB-INF/static/" + filename)));
            try {
                file.transferTo(dest);
                Map<String, Object> map = new HashMap<>();
                map.put("filename", filename);
                StringBuffer url      = request.getRequestURL();
                String       host     = url.substring(0, url.indexOf("/", 8));
                map.put("download", host + "/download/" + filename);

                return ResponseWarp.ok(map);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return ResponseWarp.error("上传出错！");
    }
}
